package com.yxjx.duoxue.my;

import java.io.IOException;

import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.Yx;
import com.yxjx.duoxue.mta.stat.StatHelper;
import com.yxjx.duoxue.network.MsgCode;
import com.yxjx.duoxue.network.NwUtils;
import com.yxjx.duoxue.network.URMobileCheckResponse;
import com.yxjx.duoxue.network.UserReg;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;
import com.yxjx.duoxue.customview.MyProgressDialog;
import com.yxjx.duoxue.datamodel.ResponseObject;

public class UserRegActivity extends BaseActionBarActivity {
	
	private Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_user_reg);
		mEditTextPhoneNum = (EditText) findViewById(R.id.phone_num);
		mEditTextPassword = (EditText) findViewById(R.id.password);
		mMobileCode = (EditText) findViewById(R.id.mobile_code);
		mGetCode = (TextView) findViewById(R.id.get_code);
		mSubmitButton = (TextView) findViewById(R.id.free_reg);
		
		mContext = this;
		
		UIHelper.setClickListener(findViewById(R.id.root), R.id.free_reg, mClickListener);
		UIHelper.setClickListener(findViewById(R.id.root), R.id.login_now, mClickListener);
		UIHelper.setClickListener(findViewById(R.id.root), R.id.get_code, mClickListener);
		UIHelper.setClickListener(findViewById(R.id.root), R.id.scroll_internal, mClickListener);
		
		mRegType = getIntent().getIntExtra(Yx.KEY_REG_TYPE, 0);
		autoFillFieldsAndGetCode(mRegType);
		if (mRegType == Yx.REG_TYPE_NEW_USER) {
			customizeActionBarTitle("注册");
			mSubmitButton.setText("免费注册");
		} else if (mRegType == Yx.REG_TYPE_GET_PWD) {
			customizeActionBarTitle("找回密码");
			mSubmitButton.setText("提交");
		}
		
		mEditTextPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
				hideIME(mEditTextPassword);
				//不同的手机平台 EditText xml设置的actionId可能不生效。
				mClickListener.onClick(findViewById(R.id.root).findViewById(R.id.free_reg));
				return false;
			}
		});
		
		StatHelper.addKVEvent(mContext, "event_my_reg_page");
		
	}

	private void autoFillFieldsAndGetCode(int regType) {
		// 自动填入用户名和密码
		String password = getIntent().getStringExtra(Yx.EXTRA_USER_PASSWORD);
		String phoneNum = getIntent().getStringExtra(Yx.EXTRA_USER_PHONE_NUM);
		if (Utils.isMobileNumber(phoneNum)) {
			mEditTextPhoneNum.setText(phoneNum);
			// 自动获取密码
			mEditTextPhoneNum.post(new Runnable() {
				@Override
				public void run() {
					mClickListener.onClick(mGetCode);
				}
			});
			//
		}
		if (Utils.isPasswordFormat(password) && regType == Yx.REG_TYPE_NEW_USER) {
//			mEditTextPassword.setText(password);
		}
	}
	
	private void reGetLater() {
		CountDownTimer timer = new CountDownTimer(60 * 1000, 1000) {
			
			@Override
			public void onTick(long arg0) {
				int reminder = (int) (arg0 / 1000);
				mGetCode.setText("" + reminder + "秒后重新获取");
				mGetCode.setClickable(false);
				mGetCode.setBackgroundResource(R.drawable.shape_grey_small_round_bg);
			}
			
			@Override
			public void onFinish() {
				mGetCode.setText("获取验证码");
				mGetCode.setClickable(true);
				mGetCode.setBackgroundResource(R.drawable.shape_green_small_round_bg);
			}
		};
		timer.start();
	}

	private View.OnClickListener mClickListener = new View.OnClickListener() {

		@Override
		public void onClick(final View arg0) {
			switch (arg0.getId()) {
			case R.id.scroll_internal:
				hideIME(arg0);
				break;
			case R.id.login_now:
//				startActivity(new Intent(getApplicationContext(), UserLoginActivity.class));
				finish();
				break;
			case R.id.get_code:
				String phoneNum1 = mEditTextPhoneNum.getText().toString();
				if (!Utils.isMobileNumber(phoneNum1)) {
					UIHelper.showTips(arg0, "手机号格式不对");
					return;
				}
				sendMobileCodeRequest(phoneNum1);
				reGetLater();
				break;
			case R.id.free_reg:
				
				final String phoneNum = mEditTextPhoneNum.getText().toString();
				final String password = mEditTextPassword.getText().toString();
				final String mobileCode = mMobileCode.getText().toString();
				if (!Utils.isMobileNumber(phoneNum)) {
					UIHelper.showTips(arg0, "手机号格式不对");
					return;
				}
				if (UIHelper.isEmpty(mobileCode)) {
					UIHelper.showTips(arg0, "注册码不能为空");
					return;
				}
				
				if (UIHelper.isEmpty(password) || password.length() < 6 || password.length() > 32) {
					UIHelper.showTips(arg0, "请输入6～32位的密码");
					return;
				}
				
				String dialogText = "正在提交";
				if (mRegType == Yx.REG_TYPE_NEW_USER) {
					dialogText = "正在注册";
				} else if (mRegType == Yx.REG_TYPE_GET_PWD) {
					dialogText = "正在找回密码";
				}
				dialog = MyProgressDialog.show(UserRegActivity.this, "", dialogText);
				
				Thread thread = new Thread(new Runnable() {
					
					@Override
					public void run() {
						try {
							
							URMobileCheckResponse rsp = UserReg.mobileCheck(phoneNum);
							if (mRegType == Yx.REG_TYPE_NEW_USER && 
									rsp.getExist() == UserReg.RSP_EXIST) {
								UIHelper.showTips(arg0, "手机号已注册过了");
							} else if (mRegType == Yx.REG_TYPE_NEW_USER) {
								ResponseObject rsp1 = UserReg.regUser(rsp, phoneNum, password, mobileCode, UserRegActivity.this);
								if (rsp1.getCode() != MsgCode.SUCCESS) {
									UIHelper.showTips(arg0, MsgCode.descFor(rsp1));
								} else {
									UIHelper.showTips(arg0, "注册成功");
									storePasswordAndUserName(phoneNum, password);
									Intent data = new Intent();
									data.putExtra(Yx.KEY_REG_TYPE, Yx.REG_TYPE_NEW_USER);
									setResult(RESULT_OK, data);
									finish();
								}
							} else if (mRegType == Yx.REG_TYPE_GET_PWD) {
								ResponseObject rspRet = UserReg.fetchPassword(rsp, phoneNum, password, mobileCode);
								if (rspRet.getCode() != MsgCode.SUCCESS) {
									UIHelper.showTips(arg0, MsgCode.descFor(rspRet));
								} else {
									UIHelper.showTips(arg0, "找回密码成功");
									StatHelper.addKVEvent(mContext, "event_my_fetch_ok");
									storePasswordAndUserName(phoneNum, password);
									Intent data = new Intent();
									data.putExtra(Yx.KEY_REG_TYPE, Yx.REG_TYPE_GET_PWD);
									setResult(RESULT_OK, data);
									finish();
								}
							} else {
								UIHelper.showTips(arg0, "发生未知错误");
							}
							
						} catch (ParseException e) {
							e.printStackTrace();
						} catch (JSONException e) {
							e.printStackTrace();
						} catch (IOException e) {
							UIHelper.showTips(arg0, "网络错误，请检查网络设置");
							e.printStackTrace();
						} finally {
							if (dialog != null) {
								dialog.dismiss();
								dialog = null;
							}
						}
						
					}
				});
				thread.start();
				break;
			default:
				mBaseClickListener.onClick(arg0);
				break;
			}
		}
	};
	
	private EditText mEditTextPhoneNum;
	private EditText mEditTextPassword;
	private TextView mGetCode;
	private EditText mMobileCode;
	private TextView mSubmitButton;
	private int mRegType;
	private ProgressDialog dialog;
	
	protected void sendMobileCodeRequest(final String number) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				ResponseObject code = new ResponseObject(-1, "");
				try {
					code = NwUtils.requestMobileCode(getApplicationContext(), number);
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (ParseException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				}
				if (code.getCode() != MsgCode.SUCCESS) {
					Utils.logd("获取验证码失败");
				} else {
					Utils.logd("获取验证码成功");
				}
			}
		}).start();
		
	}

	private void storePasswordAndUserName(String phoneNum, String password) {
		Utils.writeToSharePreference(getApplicationContext(), 
				Yx.KEY_PHONE_NUM, phoneNum);
		Utils.writeToSharePreference(getApplicationContext(),
				Yx.KEY_PHONE_PASSWORD, password);
	}
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
		};
	};
	
}
